package com.pswv2.websocket;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArrayList;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Component;

@Component
@ServerEndpoint("/websocket/{vmcNo}") // 客户端URI访问的路径
public class WebSocketServer {
	private static int online_num = 0;
	private static CopyOnWriteArrayList<WebSocketServer> sWebSocketServers = new CopyOnWriteArrayList<>();
	private Session mSession; // 与客户端连接的会话，用于发送数据
	private int mVmcNo; // 客户端的标识(这里以机器编号)
	@OnOpen
	public void onOpen(Session session,@PathParam("vmcNo") int vmcNo){
		online_num++;
		mSession = session;
		sWebSocketServers.add(this); // 将回话保存
	}
	@OnClose
	public void onClose(){
		sWebSocketServers.remove(this);
	}

	@OnMessage
	public void onMessage(String message, Session session){
		for (WebSocketServer socketServer : sWebSocketServers){
			socketServer.sendMessage("i have rcv you message");
		}
	}

	/** 对外发送消息
	 * @param message
	 */
	public boolean sendMessage(String message){
		try {
			mSession.getBasicRemote().sendText(message);
		} catch (IOException e) {
			return false;
		}
		return true;
	}
	
	/** 检查是打开webSocket
	 * @param message
	 */
	public static boolean checkUp(int vmcNo){
		boolean success = false;
		for (WebSocketServer server : sWebSocketServers){
			if (server.mVmcNo==vmcNo){
				success=true;
				System.out.println("动工");
				break;
			}
		}
		return success;
	}
	
	/** 给所有人发信息
	 * @param message
	 * @param vmcNo 机器编号
	 * @return true,返回发送的消息,false，返回failed字符串
	*/
	public static String massHair(String message, int vmcNo){
	boolean success = false;
	for (WebSocketServer server : sWebSocketServers){
			if (server.mVmcNo!= vmcNo){
			success = server.sendMessage(message);
			}
		}
		return success ? message : "failed";
	}
	
	/** 除自己发过来的给所有人群发
	 * @param message
	 * @param vmcNo 机器编号
	 * @return true,返回发送的消息,false，返回failed字符串
	*/
	public static String noMemassHair(String message, int vmcNo){
	boolean success = false;
	for (WebSocketServer server : sWebSocketServers){
			if (server.mVmcNo!= vmcNo){
			success = server.sendMessage(message);
			}
		}
		return success ? message : "failed";
	}
	
	/** 指定发送
	 * @param message
	 * @param vmcNo 机器编号
	 * @return true,返回发送的消息,false，返回failed字符串
	*/
	public static String sendMessage1(String message, int vmcNo){
	boolean success = false;
	for (WebSocketServer server : sWebSocketServers){
			if (server.mVmcNo == vmcNo){
			success = server.sendMessage(message);
			break;
			}
		}
		return success ? message : "failed";
	}
}
